import pymysql


# 实现连接类方法和通用表操作方法
class MysqlConnect:
    # 初始化数据库
    def __init__(self):
        self.connection = pymysql.connect(host='8.138.95.218', port=3306, user='hot_analysis', passwd='123456',
                                          db='hot_analysis', charset='utf8mb4')
        self.cur = self.connection.cursor()

    def query(self, sql):
        self.connection.ping(reconnect=True)
        self.cur.execute(sql)
        results = self.cur.fetchall()
        # print(type(results))  # 返回<class 'tuple'> tuple元组类型
        self.connection.commit()
        return results

    def update(self, sql, args):
        self.connection.ping(reconnect=True)
        # 携程修改的sql
        self.cur.execute(sql, args)
        self.connection.commit()

    # 封装插入数据到数据库
    def insert(self, sql, args):
        self.connection.ping(reconnect=True)
        result = self.cur.execute(sql, args)
        # print(result)
        self.connection.commit()
